#include "mainwindow.h"
#include "ui_mainwindow.h"

#include<QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("简单的记事本");

    //获取菜单栏
    QMenuBar*menuBar = this->menuBar();


    //添加菜单
    QMenu *menu = new QMenu("文件");
    menuBar->addMenu(menu);

    //添加菜单项
    QAction*actio1 = new QAction("打开");
    QAction*actio2 = new QAction("保存");
    menu->addAction(actio1);
    menu->addAction(actio2);

    //指定一个输入框
    QPlainTextEdit*edit = new QPlainTextEdit();
    QFont font;
    font.setPixelSize(20);
    edit->setFont(font);

    this->setCentralWidget(edit);

    //连接QAction的信号槽
    connect(actio1,&QAction::triggered,this,&MainWindow::handleAction1);
    connect(actio2,&QAction::triggered,this,&MainWindow::handleAction2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleAction1()
{
    //1.先弹出打开文件对话框  让用户选择打开那个文件
    QString path = QFileDialog::getOpenFileName(this);

    //2.把文件名显示到状态栏
    QStatusBar*statusbar = this->statusBar();
    statusbar->showMessage(path);

    //根据用户选择的文件构建一个QFile对象,并打开文件

    QFile file(path);
    bool ret = file.open(QIODevice::ReadOnly);
    if(!ret)
    {
        statusbar->showMessage(path + "打开失败");
        return;
    }

    //读取文件
    QString text =  file.readAll();

    //关闭文件
    file.close();


    //独到的内容设置到输入框
    edit->setPlainText(text);
}
void MainWindow::handleAction2()
{
    //1.先弹出打开文件对话框  让用户选择打开那个文件
    QString path = QFileDialog::getOpenFileName(this);

    //2.把文件名显示到状态栏
    QStatusBar*statusbar = this->statusBar();
    statusbar->showMessage(path);

    //根据用户选择的文件构建一个QFile对象,并打开文件

    QFile file(path);
    bool ret = file.open(QFile::WriteOnly);
    if(!ret)
    {
        statusbar->showMessage(path + "打开失败");
        return;
    }

    //写文件
    const QString&text = edit->placeholderText();
    file.write(text.toUtf8());
    file.close();
}

